<?php
require 'TVB/pms/pdes/common/bootstrap.php';
require_once 'TVB/VideoInfrastructure/Client/requires.php';

empty($_REQUEST['episode_id']) && exit('episode id is null');

$format = empty($_REQUEST['format']) ? 'json' : $_REQUEST['format'];
$episode_id = (int)$_REQUEST['episode_id'];

$sql = '
	SELECT v.id,v.vi_status,vl.language_id,vl.title,v.thumbnail_url thumb,v.source_url src,video_params as download_url
	FROM video v 
	INNER JOIN `video-language` vl ON v.id=vl.video_id 
	INNER JOIN `episode-video` ev ON ev.video_id=v.id
	WHERE ev.episode_id = :id
';

$_vids = Model::selectBySql($sql,array(':id'=>$episode_id));

$vids = array();
if($_vids)
{
    foreach($_vids as $key =>$val)
    {
        
        if('1' == $val['language_id'] && '' != $val['title'])
        {
            $vids[$val['id']] = $val;
        }
        else if('2' == $val['language_id'])
        {
            
            $c_id = $val['id'];
            if(empty($vids[$c_id]))
            {
                if(empty($val['title']))
                {
                    $val['title'] = 'no title';
                    $vids[$val['id']] = $val;
                }
                else
                {
                    $vids[$val['id']] = $val;
                }
            
            }
            
        }
    }
}

$vi_client = new VideoInfrastructureClient();
array_walk($vids,'getDownloadUrl',$vi_client);
function getDownloadUrl(&$value,$key,$vi){
	if($value['download_url']){
		$param = json_decode($value['download_url'],1);
		$value['download_url'] = $vi->getExportVideoUrlEasily($param['export_id']);
	}
	if(AC::VIDEO_STATUS_UPLOADED != $value['vi_status']){
		switch($value['vi_status']){
		case AC::VIDEO_STATUS_QUEUE :
			$value['thumb'] = AC::PDES_FLASH_ASSETS_PROCESS;
			break;
		case AC::VIDEO_STATUS_WAITING :
			$value['thumb'] = AC::PDES_FLASH_ASSETS_WAIT;
			break;
		case AC::VIDEO_STATUS_FAILED  :
			$value['thumb'] =  AC::PDES_FLASH_ASSETS_FAILURE; 
			break;
		}
	}
}


if('json' == $format){
	echo json_encode($vids);
}
else if('html' == $format){
	$str_item_list   = '';

	foreach($vids as $item){
		$str_item_list .= '<li><div>';
		$str_item_list .= '<input type="hidden" name="download_url" value="'.$item['download_url'].'">';
		$str_item_list .= '<input type="hidden" name="id" value="'.$item['id'].'">';
		if($item['vi_status'] == AC::VIDEO_STATUS_UPLOADED){
			$str_item_list .= '<a class="select" href="'.$item['src'].'" title="Click to select">';
		}else{
			$str_item_list .= '<a>';
		}
		$str_item_list .= '<img src="'.$item['thumb'].'" /></a>';
		$str_item_list .= '<p title="'.$item['title'].'">'.mb_strimwidth($item['title'],0,20,'...','utf8').'</p>';
		$str_item_list .= '</div></li>';
	}
	echo $str_item_list;
}
?>
